package com.xxxt.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.xxxt.utils.TokenUtil;

/**
 * 登录过滤器，所有请求都判断，是静态页面则放行（.html/.wxml）
 * @author 星梦
 *
 */
@WebFilter("/LoginFilter")
public class WcLoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public WcLoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * 判断电脑端的session是否存在
	 * 或者判断微信端的token是否存在并且是否正确
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		req.setCharacterEncoding("utf-8");
		res.setCharacterEncoding("utf-8");
		res.setContentType("charset=utf-8");		
		String token = req.getHeader("Authorization");
		boolean result = TokenUtil.verify(token);
		if((token!=null&&result)){
			chain.doFilter(request, response);
			return;
		}else{
			String url=req.getServletPath();
			if(url.contains(".wxml")||url.contains("/wx/login")){
				chain.doFilter(request, response);
				return;
			}else{
				JSONObject json = new JSONObject();
				int status=-1;
				String message="登录之后才可以操作";
				json.put("status", status);
				json.put("message", message);
				responseMessage(res, res.getWriter(), json);
				return;
			}
		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
	/**
	 * 返回信息给客户端
	 *
	 * @param response
	 * @param out
	 * @param apiResponse
	 */
	private void responseMessage(HttpServletResponse response, PrintWriter out, JSONObject jsonObject) {
		response.setContentType("application/json; charset=utf-8");
		out.print(jsonObject);
		out.flush();
		out.close();
	}
}
